package com.jcgyl.export.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jcgyl.export.entity.Tbsysuser;
import com.jcgyl.export.service.UserInfoService;
import com.jcgyl.export.util.PasswordHelper;
import com.jcgyl.export.util.entity.JsonResult;
import com.jcgyl.export.util.entity.JsonUtil;
import com.jcgyl.export.util.entity.PageResult;

@Controller
@RequestMapping("/passport/")
public class PosspostController {

	@Autowired
	private UserInfoService userInfoService;
	@RequestMapping("login")
	public String index() {
		return "passport/login";
	}
	@RequestMapping("logout")
	public String logout() {
		return "passport/logout";
	}
	/**
	 * 根据名字查询用户记录数
	 * @param name
	 * @return
	 * JL
	 */
	@RequestMapping("doFindName")
	@ResponseBody
	public PageResult doFindName(@RequestBody String name) {
		String uname = name;
		System.out.println("controllername:"+uname);
		int row =userInfoService.findName(uname);
		
		System.out.println(row);
		PageResult jsonResult = new PageResult();
		jsonResult.setResult(row);
		return jsonResult;
	}
	/**
	 * 用户登录
	 * @param posspostModel
	 * @param session
	 * @return
	 * JL
	 */
	@RequestMapping("doFindNameByPw")
	@ResponseBody
	public JsonResult doFindNameByPw(@RequestBody Tbsysuser posspostModel,HttpSession session) {
		//获取前端传入的数据
		String uname = posspostModel.getUname();
		String password = posspostModel.getPassword();
		//用户名密码封装到UsernamePasswordToken中
		 UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(uname,password);
	        Subject subject = SecurityUtils.getSubject();
	      //  if(subject.isAuthenticated())return JsonUtil.error(1, "系统异常");
	        try {
	            subject.login(usernamePasswordToken);   //完成登录
	           // SecurityUtils.getSubject().getSession().setAttribute("user",usernamePasswordToken);
	            return JsonUtil.success();
	        } catch(IncorrectCredentialsException ice) {
	        	return JsonUtil.error(2, "密码错误！");
	        }catch(AuthenticationException ae) {
	        	ae.printStackTrace();
	        	return JsonUtil.error(3, "认证错误！");
	        }
		
	}
}
